<script setup lang="ts">
  import Write from './components/Write.vue'
  import { ContentDetailWrap } from '@/components/ContentDetailWrap'
  import { ref, unref, computed } from 'vue'
  import { useI18n } from '@/hooks/web/useI18n'
  import { useRouter, useRoute } from 'vue-router'
  import { saveDataApi } from '@/api/customer'
  import { useEventBus } from '@/hooks/event/useEventBus'
  import { ElMessage } from 'element-plus'
  import { getEnumApi } from '@/api/customerFollow'

  const { emit } = useEventBus()
  const { push, go } = useRouter()
  const { query } = useRoute()
  const { t } = useI18n()

  const writeRef = ref<ComponentRef<typeof Write>>()
  const loading = ref(false)

  // 跟进记录状态
  const follow_form = ref({
    follow_method: '',
    follow_time: '',
    follow_content: ''
  })
  const follow_methodList = ref<Array<Record<string, any>>>([])

  // 表单联动验证
  const followValidationError = ref(false)
  const isFollowFilled = computed(() => {
    return (
            follow_form.value.follow_method ||
            follow_form.value.follow_time ||
            follow_form.value.follow_content
    )
  })
  const isFollowComplete = computed(() => {
    return (
            follow_form.value.follow_method &&
            follow_form.value.follow_time &&
            follow_form.value.follow_content
    )
  })

  // 初始化枚举
  const initFollowEnums = async () => {
    const resp = await getEnumApi({ field: 'all' })
    follow_methodList.value = resp.data.follow_method || []
  }
  initFollowEnums()

  // 保存方法
  const save = async () => {
    if (isFollowFilled.value && !isFollowComplete.value) {
      followValidationError.value = true
      ElMessage.error('跟进记录：一旦填写任一字段，则跟进方式、拜访时间和跟进内容必须全部填写')
      return
    }

    const write = unref(writeRef)
    const formData = (await write?.submit()) as any

    if (formData.cusnature === 1 && !formData.company_name)
      return ElMessage.error('客户性质为企业客户时，企业名称为必填。')

    if (formData) {
      const combinedData = {
        ...formData,
        follow_info: isFollowComplete.value ? { ...follow_form.value } : null
      }

      loading.value = true
      try {
        const res = await saveDataApi(combinedData)
        if (res) {
          ElMessage.success('客户信息' +
                  (isFollowComplete.value ? '及跟进记录' : '') +
                  '创建成功')
          emit('getList', 'add')
          push('/customer' + query.source)
        }
      } catch {}
      finally {
        loading.value = false
      }
    }
  }
</script>

<template>
  <ContentDetailWrap :title="t('customer.add')" @back="push('/customer/customerList')">
    <Write ref="writeRef" />

    <!-- 优化后的跟进记录部分，与图片一致 -->
    <el-divider class="mt-20px mb-20px" />

    <div class="follow-section" :class="{ 'validation-error': followValidationError }">
      <h3 class="section-title">
       跟进记录
        <span class="tip" v-if="isFollowFilled">(全部填写)</span>
        <span class="tip" v-else>(可选)</span>
      </h3>

      <div class="follow-container">
        <!-- 左侧列：跟进方式和拜访时间 -->
        <div class="left-col">
          <div class="follow-field">
            <label class="follow-label">跟进方式：</label>
            <el-select
                    v-model="follow_form.follow_method"
                    placeholder="请选择"
                    clearable
                    @change="followValidationError = false"
            >
              <el-option
                      v-for="item in follow_methodList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
              />
            </el-select>
          </div>

          <div class="follow-field mt-15px">
            <label class="follow-label">拜访时间：</label>
            <el-date-picker
                    v-model="follow_form.follow_time"
                    type="datetime"
                    placeholder="请选择时间"
                    format="YYYY/MM/DD HH:mm"
                    value-format="YYYY-MM-DD HH:mm"
                    @change="followValidationError = false"
            />
          </div>
        </div>

        <!-- 右侧列：跟进内容 - 标签与输入框同一行 -->
        <div class="right-col">
          <div class="follow-field follow-content">
            <label class="follow-label">跟进内容：</label>
            <el-input
                    v-model="follow_form.follow_content"
                    type="textarea"
                    placeholder="请输入跟进内容"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    @input="followValidationError = false"
            />
          </div>
        </div>
      </div>
    </div>

    <template #header>
      <BaseButton @click="go(-1)">{{ t('action.back') }}</BaseButton>
      <BaseButton type="primary" :loading="loading" @click="save">
        {{ t('action.save') }}
      </BaseButton>
    </template>
  </ContentDetailWrap>
</template>

<style lang="less" scoped>
  :deep(.el-upload-list__item) {
    width: 500%;
  }

  /* 精确匹配图片样式的跟进记录部分 */
  .follow-section {
    padding: 15px 20px;
    background: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 4px;

    &.validation-error {
      border: 1px solid #ff4d4f;
      animation: shake 0.5s;
    }

    .section-title {
      font-size: 15px;
      font-weight: 600;
      color: #333;
      margin-bottom: 18px;
      display: flex;
      align-items: center;

      .tip {
        margin-left: 10px;
        font-size: 12px;
        font-weight: normal;
        color: #909399;
      }
    }

    .follow-container {
      display: flex;
      gap: 20px;
    }

    .left-col {
      flex: 0 0 50%;
    }

    .right-col {
      flex: 1;
    }

    .follow-field {
      display: flex;
      align-items: center;

      .follow-label {
        flex: 0 0 70px;
        text-align: right;
        padding-right: 12px;
        color: #606266;
        white-space: nowrap;
        font-size: 14px;
      }

      .el-select,
      .el-date-picker {
        flex: 1;
      }
    }

    /* 跟进内容特殊样式 - 标签与输入框在同一行 */
    .follow-content {
      display: flex;
      align-items: flex-start;

      .follow-label {
        text-align: right;
        padding-top: 6px;
      }

      :deep(.el-textarea) {
        min-height: 60px;
        border-radius: 4px;

        .el-textarea__inner {
          min-height: 60px !important;
          max-height: 80px;
          resize: vertical;
        }
      }
    }

    @keyframes shake {
      0%, 100% {transform: translateX(0);}
      20%, 60% {transform: translateX(-5px);}
      40%, 80% {transform: translateX(5px);}
    }
  }

  /* 分隔线样式优化 */
  .el-divider {
    margin: 20px 0 !important;
    background-color: #f0f2f5;
  }
</style>